package com.atguigu.lease.web.admin.service.impl;

import com.atguigu.lease.common.exception.StgyException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.lease.model.entity.LabelInfo;
import com.atguigu.lease.web.admin.service.LabelInfoService;
import com.atguigu.lease.web.admin.mapper.LabelInfoMapper;
import org.springframework.stereotype.Service;

/**
 * @author gqs
 * @description 针对表【label_info(标签信息表)】的数据库操作Service实现
 * @createDate 2023-07-24 15:48:00
 */
@Service
public class LabelInfoServiceImpl extends ServiceImpl<LabelInfoMapper, LabelInfo>
    implements LabelInfoService {

  @Override
  public boolean saveOrUpdateLabel(LabelInfo labelInfo) {
    // 唯一性校验 type + name 组合唯一
    Long id = labelInfo.getId() == null ? -1 : labelInfo.getId();
    LabelInfo dblabelInfo =
        this.getOne(
            Wrappers.lambdaQuery(LabelInfo.class)
                // 前端传来的type是数字 后端用对应的枚举值接收 实体类的type是枚举值 数据库存的都是枚举值对应的数字
                .eq(LabelInfo::getType, labelInfo.getType().getCode())
                .eq(LabelInfo::getName, labelInfo.getName())
                .last("limit 1"));
    if (dblabelInfo != null && !dblabelInfo.getId().equals(id)) {
      throw new StgyException(ResultCodeEnum.LABEL_EXISTS_ERROR);
    }
    return this.saveOrUpdate(labelInfo);
    // return this.saveOrUpdateLabel(labelInfo); 会造成无限递归 导致栈溢出
  }
}
